package net.example.utils.android;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.ArrayMap;

import net.example.ggtalk.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.NOTIFICATION_SERVICE;


/***
 * 安卓工具类
 */
public class AndroidUtil {

    private static ProgressDialog progressDialog;
    /*
     * 提示加载
     */
    public static void showProgressDialog(Context mContext,String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(mContext, title,
                    message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /*
     * 隐藏提示加载
     */
    public static void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    private static int isSpeakerphoneOnValue=-1;//第一次获取时会将该值设置。 -1表示还未设置过扬声器

    /**
     * 扬声器是否是打开的
     * @param mContext
     * @return
     */
    public static boolean isSpeakerphoneOn(Context mContext) {
        if (isSpeakerphoneOnValue == -1) {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            isSpeakerphoneOnValue = audioManager.isSpeakerphoneOn() ? 1 : 0;
        }
        return isSpeakerphoneOnValue == 1;
    }

    //打开扬声器
    public static  int OpenSpeaker(Context mContext) {
        int currVolume = 0;
        try {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            //audioManager.setMode(AudioManager.ROUTE_SPEAKER);
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

            if (!audioManager.isSpeakerphoneOn()) {
                audioManager.setSpeakerphoneOn(true);
                int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, maxVolume,AudioManager.STREAM_VOICE_CALL);
            }
            isSpeakerphoneOnValue=1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currVolume;
    }

    public static int getCurrentVolume(Context mContext) {
        int currVolume = 0;
        try {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            //audioManager.setMode(AudioManager.ROUTE_SPEAKER);
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currVolume;
    }

    //关闭扬声器
    public static void CloseSpeaker(Context mContext, int currVolume) {

        try {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            if (audioManager != null) {
                if (audioManager.isSpeakerphoneOn()) {
                    audioManager.setSpeakerphoneOn(false);
                    audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume,
                            AudioManager.STREAM_VOICE_CALL);
                }
                isSpeakerphoneOnValue = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Toast.makeText(context,"扬声器已经关闭",Toast.LENGTH_SHORT).show();
    }


    private void setSpeakerphoneOn(Context mContext,boolean on) {

        AudioManager audioManager = (AudioManager) mContext.getSystemService (Context.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_IN_CALL);
        try {
            //播放音频流类型
            audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
            //获得当前类
            Class audioSystemClass = Class.forName("android.media.AudioSystem");
            //得到这个方法
            Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
            if (on) {
                audioManager.setMicrophoneMute(false);
                audioManager.setSpeakerphoneOn(true);
                audioManager.setMode(AudioManager.MODE_NORMAL);
            } else {
                audioManager.setSpeakerphoneOn(false);
                audioManager.setMode(AudioManager.MODE_NORMAL);
                setForceUse.invoke(null, 0, 0);
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取当前活动的页面
     * @return
     */
    public static Activity getActivity() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = null;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // 4.4 以下使用的是 HashMap
                activities = (HashMap) activitiesField.get(activityThread);
            }else{ // 4.4 以上使用的是 ArrayMap
                activities = (ArrayMap) activitiesField.get(activityThread);
            }
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused"); // 找到 paused 为 false 的activity
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            return className.equals(cpn.getClassName());
        }
        return false;
    }

    /***
     * 应用程序当前是在前台还是后台
     * @param context
     * @return
     */
    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    /**
     * 将本应用置顶到最前端
     * 当本应用位于后台时，则将它切换到最前端
     *
     * @param context
     */
    public static void setTopApp(Context context ,final  Class Class) {
        if (isAppIsInBackground(context)) {
            /**获取ActivityManager*/
            ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);

            /**获得当前运行的task(任务)*/
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                /**找到本应用的 task，并将它切换到前台*/
                if (taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
                    activityManager.moveTaskToFront(taskInfo.id,ActivityManager.MOVE_TASK_WITH_HOME);
//                    Intent intent = new Intent(context, Class);
//                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
//                    intent.setAction(Intent.ACTION_MAIN);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                    context.startActivity(intent);
                    break;
                }
            }
        }
    }

//    /**
//     * 高版本：获取顶层的activity的包名
//     *
//     * @return
//     */
//    private String getHigherPackageName() {
//        String topPackageName = "";
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
//            long time = System.currentTimeMillis();
//            //time - 1000 * 1000, time 开始时间和结束时间的设置，在这个时间范围内 获取栈顶Activity 有效
//            List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
//            // Sort the stats by the last time used
//            if (stats != null) {
//                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
//                for (UsageStats usageStats : stats) {
//                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
//                }
//                if (mySortedMap != null && !mySortedMap.isEmpty()) {
//                    topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
//                    Log.e("TopPackage Name", topPackageName);
//                }
//            }
//        } else {
//            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//            ComponentName topActivity = activityManager.getRunningTasks(1).get(0).topActivity;
//            topPackageName = topActivity.getPackageName();
//        }
//        return topPackageName;
//    }


    /**
     * 判断本应用是否已经位于最前端
     *
     * @param context
     * @return 本应用已经位于最前端时，返回 true；否则返回 false
     */
    public static boolean isRunningForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();
        /**枚举进程*/
        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfoList) {
            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 如果是后台显示通知信息
     * 显示通知信息
     *
     * @param text
     */
    public static void showNotifyMessageWhenBackground(Context context,PendingIntent pendingIntent, String title, String text) {

        if (isAppIsInBackground(context)) {
            showNotifyMessage(context,pendingIntent,title, text,0);
        }
    }

    /**
     * 消息通知管理器
     * */
    private static NotificationManager notificationManager;
    /**
     * 初始化通知管理器
     * */
    public static void initNotificationManager(Context context)
    {
        notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = context.getString(R.string.channelId_chat);
            String channelName = context.getString(R.string.channelName_chat);
            createNotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        }
    }

    /**
     * 向通知管理器中添加通道
     * */
    @TargetApi(Build.VERSION_CODES.O)
    private static void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.setDescription("聊天通知消息");
        notificationManager.createNotificationChannel(channel);
    }

    /***
     *
     * 显示通知提醒
     * @param context
     * @param pendingIntent
     * @param title
     * @param text
     */
    public static void showNotifyMessage(Context context, PendingIntent pendingIntent,String title, String text,int msgCount) {
        if(notificationManager==null)
        {
            initNotificationManager(context);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,context.getString(R.string.channelId_chat));//指定消息通道
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置图标
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));//设置图标
        builder.setTicker("有新的消息");//手机状态栏的提示
        builder.setContentTitle(title);//设置标题
        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        builder.setCategory(Notification.CATEGORY_MESSAGE);//通知的类型
        builder.setContentText(text);//设置通知内容
        builder.setWhen(System.currentTimeMillis());//设置通知时间
        builder.setContentIntent(pendingIntent);//点击后的意图
        //  builder.setFullScreenIntent(pendingIntent,true);//悬浮的
        builder.setAutoCancel(true);//点击后自动消失
        builder.setNumber(msgCount);
        builder.setDefaults(NotificationCompat.DEFAULT_ALL );//设置指示灯
        ///setPriority() 方法共有5个等级：
        //1. PRIORITY_MIN - 最低级别（-2）；
        //2. PRIORITY_LOW - 较低级别（-1）；
        //3. PRIORITY_DEFAULT - 默认级别（0）；
        //4. PRIORITY_HIGH - 较高级别（1）；
        //5. PRIORITY_MAX - 最高级别（2）；
        //当发出此类型的通知时，通知会以悬挂的方法显示在屏幕上。
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        Notification notification = builder.build();//4.1以上，以下要用getNotification()
        notificationManager.notify(1, notification);
    }



}
